from datetime import datetime
import random
import re

from Program.lib.yuntongxun.sms import CCP
from Program.models import User
from . import passport_blu
from flask import make_response, current_app, jsonify, session
from flask import request
from Program import constants, db
from Program import redis_store
from Program.utils.captcha.captcha import captcha
from Program.utils.response_code import RET


# 获取图片验证码
@passport_blu.route('/image_code')
def get_image_code():
    code_id = request.args.get('code_id')
    image_name, image_code, image_data = captcha.generate_captcha()
    try:
        redis_store.setex('ImageCode_' + code_id, constants.IMAGE_CODE_REDIS_EXPIRES, image_code)
    except Exception as e:
        current_app.logger.error(e)
        return make_response(jsonify(errno=RET.DATAERR, errmsg="保存图片失败"))

    resp = make_response(image_data)
    resp.headers['Content_type'] = 'image/jpg'
    return resp


# 获取短信验证码
@passport_blu.route('/smscode', methods=['POST'])  # 注意修改请求方式
def send_sms():
    """
        1. 接收参数并判断是否有值
        2. 校验手机号是正确
        3. 通过传入的图片编码去redis中查询真实的图片验证码内容
        4. 进行验证码内容的比对
        5. 生成发送短信的内容并发送短信
        6. redis中保存短信验证码内容
        7. 返回发送成功的响应
        :retu
    """
    param_dict = request.json  # 通过ajax通讯,接收json的值
    mobile = param_dict.get('mobile', '')
    image_code = param_dict.get('image_code', '')
    image_code_id = param_dict.get('image_code_id', '')

    if not all([mobile, image_code_id, image_code]):
        current_app.logger.error('参数不足')
        return jsonify({'errno': RET.PARAMERR, 'errmsg': '参数不全'})

    if not re.match("^1[35678][0-90]{9}$", mobile):
        return jsonify(errno=RET.DATAERR, errmsg="手机号格式错误")

    try:
        real_image_code = redis_store.get("ImageCode_" + image_code_id)
        if real_image_code:
            # real_image_code = real_image_code.decode()    已在创建时将获取的二进制数据解码
            redis_store.delete("ImageCode_" + image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取图片验证码失败")
    print(image_code)
    print(real_image_code)
    if not real_image_code:
        return jsonify(errno=RET.NODATA, errmsg="验证码已实效")

    if image_code.lower() != real_image_code.lower():
        return jsonify(errno=RET.DATAERR, errmsg="验证码输入错误")

    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmdg='数据查询错误')
    if user:
        return jsonify(errno=RET.PARAMERR, errmsg='该手机已注册')

    random_num = random.randint(0, 999999)
    sms_num = "%06d" % random_num
    current_app.logger.debug("短信验证码的页面实现内容:%s" % sms_num)
    result = CCP().send_template_sms(mobile, {sms_num, 5}, 1)

    if result != 0:
        return jsonify(errno=RET.THIRDERR, errmsg="短信发送失败")

    try:
        redis_store.set("SMS_" + mobile, sms_num, constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        return jsonify(errno=RET.DBERR, errmsg="保存验证码失败")
    return jsonify(errno=RET.OK, errmsg="发送成功")


# 注册模块实现
@passport_blu.route('/register', methods=['POST'])
def register():
    """
   1. 获取参数和判断是否有值
   2. 从redis中获取指定手机号对应的短信验证码的
   3. 校验验证码
   4. 初始化 user 模型，并设置数据并添加到数据库
   5. 保存当前用户的状态
   6. 返回注册的结果
   :return:
   """

    json_data = request.json
    mobile = json_data.get("mobile","")
    sms_code = json_data.get("smscode","")
    password = json_data.get("password","")

    if not all([mobile, sms_code, password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not re.match("^1[35678][0-90]{9}$", mobile):
        current_app.logger.error("手机号格式错误")
        return jsonify(errno=RET.PARAMERR, errmsg="手机号格式错误")

    try:
        real_sms_code = redis_store.get('SMS_' + mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取本地验证码失败")

    if not real_sms_code:
        return jsonify(errno=RET.NODATA, errmsg="验证码失效")
    if sms_code != real_sms_code:
        return jsonify(errno=RET.DATAERR, errmsg="短信验证码错误")

    try:
        redis_store.delete("SMS_" + mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='删除验证码失败')

    user = User()
    user.nick_name = mobile
    user.mobile = mobile
    user.password = password
    # 更新最后一次登陆时间
    user.last_login = datetime.now()
    # todo 密码加密
    user.password = password  # 通过底层调研models内部的property和setter方法,为user的hash_password属性设置值

    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="数据保存错误")

    # 一般需求,自动登陆,保存用户登陆状态
    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    session["mobile"] = user.mobile

    # 返回成功
    return jsonify(errno=RET.OK, errmsg="注册成功")


# 登陆模块的实现
@passport_blu.route("/login", methods=['POST'])
def login():
    json_data = request.json
    mobile = json_data.get("mobile")
    password = json_data.get("password")

    if not all([mobile, password]):
        return jsonify(errno=RET.PARAMERR, errmsg="缺少参数")

    if not re.match("^1[35678][0-90]{9}$", mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号格式错误")

    try:
        user = User.query.filter_by(mobile=mobile).first()
        print(user)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询用户异常")

    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")

    if not user.check_passowrd(password):
        return jsonify(erno=RET.PWDERR, errmsg='密码输入错误')

    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    session["mobile"] = user.mobile
    user.last_login = datetime.now()
    # 逻辑优化：如果是管理员进入到前台页面，状态保持信息中需要有is_admin
    if user.is_admin:
        session["is_admin"] = True
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)

    return jsonify(errno=RET.OK, errmsg='OK')


# 退出功能实现
@passport_blu.route("/login_out", methods=['POST'])
def login_out():
    session.pop('user_id')
    session.pop('nick_name')
    session.pop('mobile')
    # 删除管理员信息
    session.pop("is_admin",None)
    return jsonify(errno=RET.OK, errmsg="退出登陆成功")
